package com.example.selflearning.service.ehcache;
import com.example.selflearning.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.ehcache.UserManagedCache;
import org.ehcache.config.builders.UserManagedCacheBuilder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * Created by yangjingzhi on 2019/5/20.
 */
@Slf4j
public class CacheAsideUserService {
    private UserManagedCache<String, UserEntity> cache;

    public CacheAsideUserService() {
        cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, UserEntity.class).build(true);
    }

    public UserEntity findUser(String id) {
        UserEntity userEntity = cache.get(id);
        if (userEntity != null) {
            log.info("get user from cache");
            return userEntity;
        }
        UserEntity user = new UserEntity(id, "info ...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        log.info("get user from db");
        cache.put(id, user);
        return user;
    }

    public UserEntity updateUser(String id ,String info){
        UserEntity user = new UserEntity(id, info); // update user
        cache.put(id, user);
        return user;
    }

    public boolean deleteUser(String id) {
        // delete user
        cache.remove(id);
        return true;
    }

    public static void main(String[] args) {
        final CacheAsideUserService service = new CacheAsideUserService();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            executorService.execute(new Runnable() {
                public void run() {
                    service.findUser("1");
                }
            });
        }
        executorService.shutdown();
    }
}
